import React, { useEffect, useState } from 'react';
import { Modal, Descriptions, Image, Tag, Tabs, Table, Progress, Timeline, Button, Space, Statistic, Row, Col, Card } from 'antd';
import { BookOutlined, UserOutlined, ClockCircleOutlined, StarOutlined, SettingOutlined } from '@ant-design/icons';
import { getCourseDetail, getCourseLessons, getCourseStudents, getCourseReviews } from '@/services/courseManagementApi';
import LessonManagement from './LessonManagement';
import moment from 'moment';

interface CourseDetailProps {
  visible: boolean;
  course?: COURSE.CourseModel;
  onCancel: () => void;
}

const CourseDetail: React.FC<CourseDetailProps> = ({ visible, course, onCancel }) => {
  const [loading, setLoading] = useState(false);
  const [courseDetail, setCourseDetail] = useState<COURSE.CourseModel | null>(null);
  const [lessons, setLessons] = useState<any[]>([]);
  const [students, setStudents] = useState<any[]>([]);
  const [reviews, setReviews] = useState<any[]>([]);
  const [lessonManagementVisible, setLessonManagementVisible] = useState(false);

  useEffect(() => {
    if (visible && course) {
      loadCourseData();
    }
  }, [visible, course]);

  const loadCourseData = async () => {
    if (!course) return;
    
    setLoading(true);
    try {
      const [detailRes, lessonsRes, studentsRes, reviewsRes] = await Promise.all([
        getCourseDetail(course.id),
        getCourseLessons(course.id),
        getCourseStudents(course.id, { limit: 10 }),
        getCourseReviews(course.id, { limit: 10 }),
      ]);

      setCourseDetail(detailRes.data);
      setLessons(lessonsRes.data || []);
      setStudents(studentsRes.data?.list || []);
      setReviews(reviewsRes.data?.list || []);
    } catch (error) {
      console.error('加载课程数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  if (!course) return null;

  const displayCourse = courseDetail || course;

  // 状态标签颜色映射
  const statusColorMap = {
    draft: 'default',
    published: 'green',
    archived: 'orange',
  };

  // 难度标签颜色映射
  const difficultyColorMap = {
    beginner: 'green',
    intermediate: 'orange',
    advanced: 'red',
  };

  // 课时表格列
  const lessonColumns = [
    {
      title: '课时标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '时长',
      dataIndex: 'duration',
      key: 'duration',
      render: (duration: number) => `${duration} 分钟`,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeMap = { video: '视频', audio: '音频', text: '文本', quiz: '测验' };
        return typeMap[type as keyof typeof typeMap] || type;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'published' ? 'green' : 'default'}>
          {status === 'published' ? '已发布' : '草稿'}
        </Tag>
      ),
    },
  ];

  // 学员表格列
  const studentColumns = [
    {
      title: '学员',
      key: 'student',
      render: (record: any) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <img
            src={record.avatar}
            alt={record.nickname}
            style={{ width: 32, height: 32, borderRadius: '50%' }}
          />
          <div>
            <div>{record.nickname}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>@{record.username}</div>
          </div>
        </div>
      ),
    },
    {
      title: '进度',
      dataIndex: 'progress_percentage',
      key: 'progress_percentage',
      render: (progress: number) => (
        <Progress percent={Math.round(progress)} size="small" />
      ),
    },
    {
      title: '最后学习',
      dataIndex: 'last_accessed_at',
      key: 'last_accessed_at',
      render: (time: string) => moment(time).format('YYYY-MM-DD HH:mm'),
    },
  ];

  // 评价表格列
  const reviewColumns = [
    {
      title: '学员',
      key: 'student',
      render: (record: any) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <img
            src={record.student_avatar}
            alt={record.student_nickname}
            style={{ width: 32, height: 32, borderRadius: '50%' }}
          />
          <div>
            <div>{record.student_nickname}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>
              {'⭐'.repeat(record.rating)}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '评价内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
    },
    {
      title: '评价时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (time: string) => moment(time).format('YYYY-MM-DD HH:mm'),
    },
  ];

  const tabItems = [
    {
      key: 'basic',
      label: '基本信息',
      children: (
        <div>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={8}>
              <Image
                src={displayCourse.cover}
                alt={displayCourse.title}
                width="100%"
                style={{ borderRadius: 8 }}
                fallback=""
              />
            </Col>
            <Col span={16}>
              <Descriptions column={1} bordered>
                <Descriptions.Item label="课程标题">{displayCourse.title}</Descriptions.Item>
                <Descriptions.Item label="副标题">{displayCourse.subtitle || '-'}</Descriptions.Item>
                <Descriptions.Item label="分类">{displayCourse.category_name}</Descriptions.Item>
                <Descriptions.Item label="难度">
                  <Tag color={difficultyColorMap[displayCourse.difficulty]}>
                    {displayCourse.difficulty === 'beginner' ? '初级' : displayCourse.difficulty === 'intermediate' ? '中级' : '高级'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={statusColorMap[displayCourse.status]}>
                    {displayCourse.status === 'draft' ? '草稿' : displayCourse.status === 'published' ? '已发布' : '已归档'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="价格">
                  {displayCourse.price > 0 ? `¥${displayCourse.price}` : '免费'}
                </Descriptions.Item>
              </Descriptions>
            </Col>
          </Row>

          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="学习人数"
                  value={displayCourse.student_count || 0}
                  prefix={<UserOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="课时数量"
                  value={displayCourse.lesson_count || 0}
                  prefix={<BookOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="课程时长"
                  value={displayCourse.duration || 0}
                  suffix="分钟"
                  prefix={<ClockCircleOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="平均评分"
                  value={displayCourse.rating || 0}
                  precision={1}
                  prefix={<StarOutlined />}
                />
              </Card>
            </Col>
          </Row>

          <Descriptions column={1} bordered>
            <Descriptions.Item label="课程简介">
              <div style={{ whiteSpace: 'pre-wrap' }}>{displayCourse.description}</div>
            </Descriptions.Item>
            <Descriptions.Item label="学习目标">
              <div style={{ whiteSpace: 'pre-wrap' }}>{displayCourse.objectives || '-'}</div>
            </Descriptions.Item>
            <Descriptions.Item label="前置要求">
              <div style={{ whiteSpace: 'pre-wrap' }}>{displayCourse.prerequisites || '-'}</div>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {moment(displayCourse.created_at).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">
              {moment(displayCourse.updated_at).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
          </Descriptions>
        </div>
      ),
    },
    {
      key: 'lessons',
      label: '课时列表',
      children: (
        <Table
          columns={lessonColumns}
          dataSource={lessons}
          rowKey="id"
          pagination={false}
          loading={loading}
          size="small"
        />
      ),
    },
    {
      key: 'students',
      label: '学员列表',
      children: (
        <Table
          columns={studentColumns}
          dataSource={students}
          rowKey="user_id"
          pagination={false}
          loading={loading}
          size="small"
        />
      ),
    },
    {
      key: 'reviews',
      label: '课程评价',
      children: (
        <Table
          columns={reviewColumns}
          dataSource={reviews}
          rowKey="id"
          pagination={false}
          loading={loading}
          size="small"
        />
      ),
    },
  ];

  return (
    <>
      <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <BookOutlined style={{ fontSize: 20 }} />
          <div>
            <div>{displayCourse.title}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>课程详情</div>
          </div>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={[
        <Button
          key="lesson-management"
          type="primary"
          icon={<SettingOutlined />}
          onClick={() => setLessonManagementVisible(true)}
        >
          课时管理
        </Button>,
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
      ]}
      width={1000}
      destroyOnClose
    >
        <Tabs items={tabItems} />
      </Modal>

      {/* 课时管理弹窗 */}
      <LessonManagement
        visible={lessonManagementVisible}
        course={displayCourse}
        onCancel={() => setLessonManagementVisible(false)}
      />
    </>
  );
};

export default CourseDetail;
